<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="num = 200">btn</button>
      <!-- 依赖注入可以将父组件的状态直接传递给子孙组件 -->
      <!-- 跨组件传参 -->

      <!-- 依赖注入在vue2的时候不推荐使用，当时没有响应式 -->
      <!-- 在vue3中解决了响应式问题，所以推荐使用 -->
      <h2>依赖注入</h2>
      <child></child>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const myInjectionKey = Symbol();

      const { createApp, computed } = Vue;
      const Child2 = {
        // inject的数组语法
        // inject: ["count"],

        // inject对象语法
        // 可以给inject取别名和默认值
        inject: {
          newCount: {
            from: myInjectionKey,
            default: 100,
          },
        },
        data() {
          return {
            count: 111,
          };
        },
        template: `
          <div>这是child2子组件 - {{ newCount }}</div>
        `,
      };

      const Child = {
        data() {
          return {};
        },
        template: `
          <div>这是child子组件</div>
          <child2></child2>
        `,
        components: {
          Child2,
        },
      };

      const app = createApp({
        data() {
          return {
            num: 20,
          };
        },
        components: {
          Child,
        },
        // provide: {
        //   count: 10,
        // },
        provide() {
          return {
            // count: this.num,
            [myInjectionKey]: computed(() => this.num),
          };
        },
      });

      app.config.unwrapInjectedRef = true;

      app.mount("#app");
    </script>
  </body>
</html>
